package com.star.common.sms.service.impl;

import com.alibaba.fastjson2.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.star.common.sms.constant.SmsConstant;
import com.star.common.sms.properties.SmsProperties;
import com.star.common.sms.service.AbstractSmsClient;
import lombok.SneakyThrows;

import java.util.Map;

/**
 * 阿里云发送短信
 *
 * @author zhouhengzhe
 * @version 1.0
 * @date 2023/6/25 14:08
 */
public class AliyunSmsClient extends AbstractSmsClient {


    private final Client client;

    @SneakyThrows
    public AliyunSmsClient(SmsProperties.AliyunSmsProperties aliyunSmsProperties) {
        Config config = new Config().setAccessKeyId(aliyunSmsProperties.getAccessKeyId()).setAccessKeySecret(aliyunSmsProperties.getAccessKeySecret());
        this.client = new Client(config);
    }

    /**
     * 发送单条信息
     *
     * @param phoneNumber    手机号码
     * @param template       模板
     * @param templateParams 模板参数
     * @param signName       签名
     * @return 发送是否成功
     */
    @Override
    public boolean sendSingle(String phoneNumber, String template, Map<String, String> templateParams, String signName) {
        super.checkParam(phoneNumber, template, templateParams, signName);
        try {
            //组装请求对象-具体描述见控制台-文档部分内容
            SendSmsRequest request = new SendSmsRequest();
            //必填:待发送手机号
            request.setPhoneNumbers(phoneNumber);
            //必填:短信签名-可在短信控制台中找到
            request.setSignName(signName);
            //必填:短信模板-可在短信控制台中找到
            request.setTemplateCode(template);
            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
            //{"name":"张三","number":"1390000****"}
            request.setTemplateParam(JSON.toJSONString(templateParams));
            //hint 此处可能会抛出异常，注意catch
            SendSmsResponse sendSmsResponse = client.sendSms(request);
            if (SmsConstant.SUCCESS_CODE.equals(sendSmsResponse.getStatusCode())) {
                SendSmsResponseBody body = sendSmsResponse.getBody();
                return SmsConstant.SUCCESS.equals(body.getCode());
            }
            return false;
        } catch (Exception error) {
            throw new RuntimeException("发送短信失败", error);
        }
    }
}
